import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DeepPartial } from 'typeorm';
import { Favorite } from './entities/favorite.entity';
import { CreateFavoriteDto } from './dto/create-favorite.dto';
import { Topic } from '../topic/entities/topic.entity';

@Injectable()
export class FavoriteService {
  constructor(
    @InjectRepository(Favorite)
    private readonly favoriteRepository: Repository<Favorite>,
    @InjectRepository(Topic)
    private readonly topicRepository: Repository<Topic>,
  ) {}

  async create(createFavoriteDto: CreateFavoriteDto) {
    const existingFavorite = await this.favoriteRepository.findOne({
      where: {
        user: { id: createFavoriteDto.userId },
        topic: { id: createFavoriteDto.topicId },
      },
    });
    if (existingFavorite) {
      return existingFavorite;
    }
    // 显式转换为 DeepPartial<Favorite> 类型
    const favoriteData: DeepPartial<Favorite> = {
      user: { id: createFavoriteDto.userId },
      topic: { id: createFavoriteDto.topicId },
    };
    const favorite = this.favoriteRepository.create(favoriteData);
    return this.favoriteRepository.save(favorite);
  }

  async findAll() {
    return this.favoriteRepository.find({ relations: ['user', 'topic'] });
  }

  async findOne(id: number) {
    const favorite = await this.favoriteRepository.findOne({
      where: { id },
      relations: ['user', 'topic'],
    });
    if (!favorite) {
      throw new NotFoundException('收藏记录不存在');
    }
    return favorite;
  }

  async remove(id: number) {
    const favorite = await this.findOne(id);
    return this.favoriteRepository.remove(favorite);
  }

  async isFavorite(userId: number, topicId: number) {
    const favorite = await this.favoriteRepository.findOne({
      where: { user: { id: userId }, topic: { id: topicId } },
    });
    return !!favorite;
  }

  async removeByUserAndTopic(userId: number, topicId: number) {
    const favorite = await this.favoriteRepository.findOne({
      where: { user: { id: userId }, topic: { id: topicId } },
    });
    if (!favorite) {
      throw new NotFoundException('收藏记录不存在');
    }
    return this.favoriteRepository.remove(favorite);
  }
  async findByUserIdWithPagination(
    userId: number,
    page: number = 1,
    size: number = 10,
  ) {
    const skip = (page - 1) * size;
    const [favorites, total] = await this.favoriteRepository.findAndCount({
      where: { user: { id: userId } },
      skip,
      take: size,
      relations: ['topic'],
    });

    const favoritesWithMediaUrl = await Promise.all(
      favorites.map(async (favorite) => {
        const topic = await this.topicRepository.findOne({
          where: { id: favorite.topic.id },
        });
        return {
          ...favorite,
          topic: topic || null,
        };
      }),
    );

    return {
      data: favoritesWithMediaUrl,
      total,
    };
  }
}
